<?php
namespace Home\Controller;
use Home\Model\ApinfoModel;
use Home\Model\SqliteApinfo;
use Think\Controller;
class ScanwifiController extends BaseController {

    public function DatabaseClearAP(){
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') . 'DatabaseClear/APInfo', null);
            $js=(json_decode($retdata, true));
            D('Apinfo')->where('1')->delete();

            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }

    public function DatabaseClearSTA(){
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') . 'DatabaseClear/STAInfo', null);
            $js=(json_decode($retdata, true));
            D('Stainfo')->where('1')->delete();

            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }

    public function getscanstatus(){
        //获取扫描子板的获取ap列表接口
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') . 'ConfigScan/status', null);
            $js=(json_decode($retdata, true));
            $this->ajaxReturn(array('scanstatus'=>$js[0]), 'JSON');
        }
    }


    public function  doscan(){
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') . 'ConfigScan/' . I('post.action'), null);
            $js=(json_decode($retdata, true));

            //$this->display('scanwifi:scanwifi');
            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }
    public function getmorscanwifi(){

    }

    public function scanwifi(){
        //设置脚本最大执行时间
        $sqliteapinfo=new SqliteApinfo();
        $apdata= $sqliteapinfo->select();

        $apinfodatable= D('Apinfo');
        $apinfodatable->where(1)->delete();
        $count=count($apdata);

        if($apdata){
            for($iloop=0; $iloop < $count; $iloop++){
                $map[$iloop]= array(
                    'ssid'=>$apdata[$iloop]['essid'],
                    'mac'=>$apdata[$iloop]['s_mac'],
                    'signalpath'=>$apdata[$iloop]['channel'],
                    'devmodel'=>$apdata[$iloop]['device_name'],
                    'ver_name'=>$apdata[$iloop]['ver_name'],
                    'time'=>$apdata[$iloop]['time'],
                    'encryption'=>str_replace("/","-",$apdata[$iloop]['en_mode'] ),
                    'signalstrength'=>$apdata[$iloop]['signal']
                );
            }
        }
        if($count){
            $apinfodatable->addAll($map);
        }

        $apinfodata = $apinfodatable->order(array( 'time'=>'desc'))->limit(1,$count)->select();
        if($apinfodata==true){
            $this->assign("scanwifidata",$apinfodata);
        }
        //获取是否有设备正在破解、攻击中
        $iscrack = $apinfodatable->where(array('iscrack'=>1))->count();
        $this->assign("iscrack",$iscrack);
        $isattack = $apinfodatable->where(array('isattack'=>1))->count();
        $this->assign("isattack",$isattack);
        $iswz = $apinfodatable->where(array('iswz'=>1))->count();
        $this->assign("iswz",$iswz);
        $this->display();

        return;

        //获取热点和终端列表
        $url=$_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') . 'APDevInfo/nil%20nil%20nil%20nil%20nil%20';

        $retwifidata = http_post_json($url, null);
        $jswifidata=(json_decode($retwifidata, true));
        if($jswifidata){
            for($iloop=0; $iloop < count($jswifidata[0]); $iloop++){
                $map= array(
                    'ssid'=>$jswifidata[0][$iloop]['ssid'],
                    'mac'=>$jswifidata[0][$iloop]['mac'],
                    'signalpath'=>$jswifidata[0][$iloop]['signalPath'],
                    'devmodel'=>$jswifidata[0][$iloop]['devmodel'],
                    'time'=>$jswifidata[0][$iloop]['time'],
                    'encryption'=>str_replace("/","-",$jswifidata[0][$iloop]['encryption'] ),
                    'signalstrength'=>$jswifidata[0][$iloop]['signalStrength']
                );
                //先查询是否存在相同ssid名称，相同mac
                if(D('Apinfo')->getSimCount($jswifidata[0][$iloop]['ssid'],  $jswifidata[0][$iloop]['mac'])<=0){
                    D('Apinfo')->add($map);
                }
                else{
                    D('Apinfo')->where(array('mac'=>$map['mac']))->save($map);
                }
            }
        }

        $apinfodata = D('Apinfo')->order(array( 'time'=>'desc'))->select();
        if($apinfodata==true){
            $this->assign("scanwifidata",$apinfodata);
        }
        //获取是否有设备正在破解、攻击中
        $iscrack = D('Apinfo')->where(array('iscrack'=>1))->count();
        $this->assign("iscrack",$iscrack);
        $isattack = D('Apinfo')->where(array('isattack'=>1))->count();
        $this->assign("isattack",$isattack);
        $iswz = D('Apinfo')->where(array('iswz'=>1))->count();
        $this->assign("iswz",$iswz);


        //获取热点和终端列表
        /*
        $retteerminaldata = http_post_json($_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') . 'TerminalDevInfo/nil%20nil%20nil%20nil%20nil%20', null);
        $jsterminaldata=(json_decode($retteerminaldata, true));

        $this->assign("scanterminaldata",$jsterminaldata[0]);
        */

        $this->display();
    }
    public function getdevlist(){
        if(IS_POST){
            //http://192.168.11.1/cgi-bin/luci/admin/wifiscan/TerminalDevInfo/nil%2088:25:93:B9:94:00%20nil%20nil%20
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL')
                . 'TerminalDevInfo/nil%20' . I('post.apmac') ."%20nil%20nil%20", null);
            $js=(json_decode($retdata, true));

            //$this->display('scanwifi:scanwifi');
            //$this->ajaxReturn(array('status'=>$js[0]), 'JSON');

            //$data=D('stainfo')->where(array('dmac'=>I('post.apmac')))->select();
            if($js){
                $this->ajaxReturn(array('status'=>true, 'data'=>$js[0]), 'JSON');
            }
            else{
                $this->ajaxReturn(array('status'=>false, 'data'=>null), 'JSON');
            }
        }
    }


    public function  scan(){
        if(IS_POST){
            $setcardstatus= [];
            $ip[0]=I('post.ip0');
            $ip[1]=I('post.ip1');
            $ip[2]=I('post.ip2');
            $ip[3]=I('post.ip3');
            for($i=0; $i < 4; $i++){
                $retdata = http_post_json( $ip[$i] . C('LUCI_STATUS_URL') . 'getStatInfo', null);
                $js=(json_decode($retdata, true));
                $setcardstatus[$i]=$js[0][0];
            }

            //$this->assign('setcardstatus', $setcardstatus);

            $this->ajaxReturn($setcardstatus, 'JSON');
        }
    }




    /////////////////////////////////////////////////////
    public function  stopPackageAct(){
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageAct/stop', null);
            $js=(json_decode($retdata, true));

            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }
    public function  startPackageAct(){
        if(IS_POST){
            $retdatas = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageDatabaseClearSTA', null);

            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageAct/start', null);
            $js=(json_decode($retdata, true));

            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }
    public function  PackageList(){
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageList', null);
            $js=(json_decode($retdata, true));

            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }
    public function  PackageClear(){
        if(IS_POST){
            $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageClear', null);
            $js=(json_decode($retdata, true));

            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }



    public function crackWiFi(){
        if(IS_POST){
            if(I('post.action')=='stop'){
                $status=I('post.action')=='start'?'1':'0';
                D('apinfo')->where(array('mac'=>I('post.apmac')))->save(array('iscrack'=>$status));
                $this->ajaxReturn(array('status'=>true), 'JSON');
            }
            else if(I('post.xd')){
                $status=I('post.action')=='start'?'1':'0';
                D('apinfo')->where(array('mac'=>I('post.apmac')))->save(array('iscrack'=>$status));
                //清除历史抓包 开始抓包---》10s---》3、停止抓包----》
                //（校验：暂时没有接口）---》4、获取到抓包文件（samba的挂载磁盘方式，先配置好固定的子板）
                // -------》5、破解调用---》6、等待返回结果数据（成功或失败）----》7、展示破解结果：成功/失败！

                //0.停止抓包
                $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageAct/stop', null);

                //1.清除历史抓包
                $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageClear', null);
                //2.开始抓包
                $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageAct/start/'.I('post.xd').'/'. I('post.apmac'), null);

                //10s
                sleep(10);
                //3.停止抓包
                $retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageAct/stop', null);

                //4.获取到抓包文件
                ////$retdata = http_post_json($_SESSION['cardinfo'][self::$cardtype_package]['cardip'] . C('LUCI_WIFISCAN_URL') . 'PackageAct/PackageList', null);
                //var_dump($retdata);
                //test.hccapx
                //crackfilepath
                //5.调用破解
                $filename='/crackpath/cap/test.hccapx';
                if (!file_exists($filename) || filesize($filename)<=0) {
                    $this->ajaxReturn(array('status'=>false, 'reason'=>'破解期间没有握手报文。'), 'JSON');
                    return;
                }

                $startcrackjson= json_encode(array('taskid'=>I('post.id'),
                    'crackfilepath'=>$filename));
                $retdata = http_post_json('http://127.0.0.1:5000/crackwifi/start', $startcrackjson);
                $retdata=(json_decode($retdata, true));
                //6.等待返回结果数据
                //7.展示破解结果：成功/失败
                //将破解的秘钥保存到apinfo表


                $this->ajaxReturn($retdata, 'JSON');

            }
            else{
                $this->ajaxReturn(array('status'=>false), 'JSON');
            }
        }
    }

    public function getcrackWiFiStatus(){
        if(IS_POST){
            $startcrackjson=json_encode(array('taskid'=>I('post.id')));
            $retdata = http_post_json('http://127.0.0.1:5000/crackwifi/status', $startcrackjson);
            $retdata=(json_decode($retdata, true));
            if($retdata['status']=='success'){
                $crackpwd= end(explode(':', $retdata['secret'])) ;
                D('apinfo')->where(array('id'=>I('post.id')))->save(array('crackpwd'=>$crackpwd));
                $status=0;
                D('apinfo')->where(array('id'=>I('post.id')))->save(array('iscrack'=>$status));

                $retdata['secret']=$crackpwd;
            }
            else if($retdata['status']=='run'){

            }else{
                $status=0;
                D('apinfo')->where(array('id'=>I('post.id')))->save(array('iscrack'=>$status));
            }

            $this->ajaxReturn($retdata, 'JSON');
        }
    }
    public  function stopcrackWiFi(){

    }

    public function getStrength(){
        if(IS_POST){
            $mac= mb_convert_case (I('post.mac'),MB_CASE_LOWER, "UTF-8");

            $url=$_SESSION['cardinfo'][self::$cardtype_scan]['cardip'] . C('LUCI_WIFISCAN_URL') .
                'GetDis/'.'%20/' .$mac;

            $retdata = http_post_json($url, null);
            $js=(json_decode($retdata, true));
            $signalstrength = $js[0];


            $signalstrength = str_replace(array("\r\n", "\r", "\n"), "", $signalstrength);
            $signalstrength = str_replace(array(" "), "", $signalstrength);
            $this->ajaxReturn(array('signalstrength'=>$signalstrength), 'JSON');
        }
    }

    public function attackWiFi(){
        if(IS_POST){
            $url=$_SESSION['cardinfo'][self::$cardtype_attack]['cardip'] . C('LUCI_WIFISCAN_URL') .
                'APAttackAct/'.I('post.action').'/'.I('post.xd').'/'. I('post.apmac');

            $retdata = http_post_json($url, null);
            $js=(json_decode($retdata, true));

            $status=I('post.action')=='start'?'1':'0';
            D('apinfo')->where(array('mac'=>I('post.apmac')))->save(array('isattack'=>$status));


            $this->ajaxReturn(array('status'=>$js[0]), 'JSON');
        }
    }

    public function WZWifi(){
        $status=I('post.action')=='start'?'1':'0';
        if(IS_POST){
            $url=$_SESSION['cardinfo'][self::$cardtype_wz]['cardip'] .
                C('LUCI_WIFISCAN_URL') . 'WZWifi/'
                . I('post.action').'/'.I('post.xd').'/'. I('post.ssid').'/'. I('post.encrypt').'/'. I('post.key');



            $retdata = http_post_json($url, null);
            $js=(json_decode($retdata, true));

            if(I('post.action')=='start'){
                //保存伪装状态
                session('wzwifi',array('ssid'=>I('post.ssid'),
                    'encrypt'=>I('post.encrypt'),
                    'ssid'=>I('post.ssid'),
                    'key'=>I('post.key'),
                    'xd'=>I('post.xd'),
                    'apmac'=>I('post.apmac')));

                D('apinfo')->where(array('mac'=>I('post.apmac')))->save(array('iswz'=>$status));
            }else{
                session('wzwifi',null);
                D('apinfo')->where(1)->save(array('iswz'=>$status));
            }

            $this->ajaxReturn(array('status'=>$js), 'JSON');
        }
    }

    public function clearwzwifi(){
        if(IS_POST){
            D('apinfo')->where(1)->save(array('iswz'=>0));
            $this->ajaxReturn(array('status'=>true), 'JSON');
        }
    }
}